package xw.qxypt.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

public class XinZhiUtil {

	private String TIANQI_DAILY_WEATHER_URL = "https://api.seniverse.com/v3/weather/daily.json";

    private String TIANQI_API_SECRET_KEY = "2ymjr04qobq90caf"; //

    private String TIANQI_API_USER_ID = "UDF83C58EF"; //
    
    private String CAIYUN_URL="https://api.caiyunapp.com/v2/";
    
    private String CAIYUN_KEY="GdAqPzhlyaZSSMI6";

    /**
     * Generate HmacSHA1 signature with given data string and key
     * @param data
     * @param key
     * @return
     * @throws SignatureException
     */
    private String generateSignature(String data, String key) throws SignatureException {
        String result;
        try {
            // get an hmac_sha1 key from the raw key bytes
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
            // get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            // compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
            result = new sun.misc.BASE64Encoder().encode(rawHmac);
        }
        catch (Exception e) {
            throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
        }
        return result;
    }

    /**
     * Generate the URL to get diary weather
     * @param location
     * @param language
     * @param unit
     * @param start
     * @param days
     * @return
     */
    public String generateGetDiaryWeatherURL(
            String location,
            String language,
            String unit,
            String start,
            String days
    )  throws SignatureException, UnsupportedEncodingException {
        String timestamp = String.valueOf(new Date().getTime());
        String params = "ts=" + timestamp + "&ttl=30&uid=" + TIANQI_API_USER_ID;
        String signature = URLEncoder.encode(generateSignature(params, TIANQI_API_SECRET_KEY), "UTF-8");
        return TIANQI_DAILY_WEATHER_URL + "?" + params + "&sig=" + signature + "&location=" + location + "&language=" + language + "&unit=" + unit + "&start=" + start + "&days=" + days;
    }
    
    public String generateGetAlarmURL(String key,String location) {
    	
    	return "https://api.seniverse.com/v3/weather/alarm.json?key="+key+ "&location="+location;
    }
    public String get24hoursWeather(String key,String location) {
    	
    	return "https://api.seniverse.com/v3/weather/hourly.json?key="+key+"&location="+location+"&language=zh-Hans&unit=c&start=0&hours=24";
    }
    /* 
     * 处理https GET/POST请求 
     * 请求地址、请求方法、参数 
     * */  
    public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){  
        StringBuffer buffer=null;  
        try{  
        //创建SSLContext  
        SSLContext sslContext=SSLContext.getInstance("SSL");  
        TrustManager[] tm={new MyX509TrustManager()};  
        //初始化  
        sslContext.init(null, tm, new java.security.SecureRandom());;  
        //获取SSLSocketFactory对象  
        SSLSocketFactory ssf=sslContext.getSocketFactory();  
        URL url=new URL(requestUrl);  
        HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();  
        conn.setDoOutput(true);  
        conn.setDoInput(true);  
        conn.setUseCaches(false);  
        conn.setRequestMethod(requestMethod);  
        //设置当前实例使用的SSLSoctetFactory  
        conn.setSSLSocketFactory(ssf);  
        conn.connect();  
        //往服务器端写内容  
        if(null!=outputStr){  
            OutputStream os=conn.getOutputStream();  
            os.write(outputStr.getBytes("utf-8"));  
            os.close();  
        }  
          
        //读取服务器端返回的内容  
        InputStream is=conn.getInputStream();  
        InputStreamReader isr=new InputStreamReader(is,"utf-8");  
        BufferedReader br=new BufferedReader(isr);  
        buffer=new StringBuffer();  
        String line=null;  
        while((line=br.readLine())!=null){  
            buffer.append(line);  
        }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
        return buffer.toString();  
    }  
    
    public String getWeatherByLatitudeAndLongitude(String Longitude,
			String Latitude, String deviceId) {
		
		//返回消息主题
		JSONObject returnResultObject=new JSONObject();
		
		try{
			returnResultObject.put("code", "0");
			returnResultObject.put("msg", "操作成功！");
			
			String forecastMes = CAIYUN_URL+ CAIYUN_KEY + "/" + Longitude
					+ "," + Latitude + "/forecast?alert=true";
			String content = "";
			content = httpsRequest(forecastMes, "GET", null);

			//logger.error(content);
			
			JSONObject obj = JSONObject.fromObject(content);

			String apiStatus = obj.get("status").toString();

			if (apiStatus.equals("ok")) {


				JSONObject result = obj.getJSONObject("result");

				JSONObject hourly = result.getJSONObject("hourly");

				String hourlyStatus = hourly.get("status").toString();

				String description = "";
				
				JSONObject minutely = result.getJSONObject("minutely");

				String minutelyStatus = minutely.get("status").toString();

				if (minutelyStatus.equals("ok")) {
					
					 description += minutely.get("description").toString();
					
					
				}
				
				if (hourlyStatus.equals("ok")) {

					
					description += "<br>"+hourly.get("description").toString();

					
				}
				
				description = description.replace("，放心出门吧", "");
				description = description.replace("您", "");
				description = description.replace("呢", "");
				description = description.replace("哦", "");
				description = description.replace("外", "");
				description = description.replace("观测资料不够了……但小彩云觉得很有可能降雨呢", "");
				description = description.replace("，出门还是带把伞吧~", "");
				description = description.replace("出门带把伞", "");
				description = description.replace("大风起兮……注意不要被风刮跑", "大风");
				description = description.replace("但", "");
				description = description.replace("不过", "");
				description = description.replace("小彩云", "");
				description = description.replace("大风起兮", "大风");
				description = description.replace("注意不要被风刮跑", "");
				returnResultObject.put("resultData", description);
			}
			  
		}catch(Exception e){
			
			returnResultObject.put("code", "1");
			returnResultObject.put("msg", "操作失败！");
		}

		return returnResultObject.toString();
	}
	
	public String getRealWeatherByLatitudeAndLongitude(String Longitude,
			String Latitude, String deviceId) {
		String realTimeMes = CAIYUN_URL+ CAIYUN_KEY +"/"+Longitude+","+Latitude+"/realtime.json";
		 String content = "";
		 content = httpsRequest(realTimeMes,"GET",null);
		return content;
	}
    public static void main(String args[]){
    	XinZhiUtil demo = new XinZhiUtil();
    			String str = demo.getRealWeatherByLatitudeAndLongitude("116.67","36.67", null);
    			System.out.println(str);
    	/*XinZhiUtil demo = new XinZhiUtil();
        try {
//            String url = demo.generateGetDiaryWeatherURL(
//                    "qingdao",
//                    "zh-Hans",
//                    "c",
//                    "1",
//                    "1"
//            );
//            System.out.println("URL:" + url);
//            
//            String aa = "https://api.seniverse.com/v3/weather/now.json?key=2ymjr04qobq90caf&location=beijing&language=zh-Hans&unit=c";
            String alarm = "https://api.seniverse.com/v3/weather/hourly.json?key=2ymjr04qobq90caf&location=qingdao&language=zh-Hans&unit=c&start=0&hours=24";
            String result = "";
            result = httpsRequest(alarm,"GET",null);
            
            System.out.println(result);
        	
            JSONObject obj = JSONObject.fromObject(result);
            
            JSONArray results = obj.getJSONArray("results");
            
            for(int i = 0;i < results.size();i++) {
            	
            	JSONObject job = results.getJSONObject(i);
            	
            	
            	JSONArray alarms = job.getJSONArray("hourly");
            	
            	for(int j = 0;j < alarms.size();j++) {
            		
            		JSONObject alarm1 = alarms.getJSONObject(j);
            		
            		System.out.println(alarm1.get("text")+"---"+DateString2formatString(alarm1.getString("time"))) ;
            	}
            }
//            JSONArray array= results.getJSONArray("alarms");    //得到为json的数组
//            
//            for(int i = 0;i < array.size();i++) {
//            	
//            	JSONObject job = array.getJSONObject(i);
//            	
//            	System.out.println(job.get("title")+"---"+DateString2formatString(job.getString("pub_date"))) ; 
//            }
//        	 DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");  //yyyy-MM-dd'T'HH:mm:ss.SSSZ  
//             Date date = df.parse("2018-01-28T15:06:00+08:00");  
//             System.out.println(DateString2formatString("2018-01-28T15:06:00+08:00"));  
        } catch (Exception e) {
            System.out.println("Exception:" + e);
        }
*/
    }
    
    public static String dealDateFormat(String oldDateStr) throws ParseException{
    	  //此格式只有  jdk 1.7才支持  yyyy-MM-dd'T'HH:mm:ss.SSSXXX          
    	  DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");  //yyyy-MM-dd'T'HH:mm:ss.SSSZ
    	  Date  date = df.parse(oldDateStr);
    	  SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
    	  Date date1 =  df1.parse(date.toString());
    	  DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	//  Date date3 =  df2.parse(date1.toString());
    	  return df2.format(date1);
    	 }
    
    /** 
     * 将格林威治时间字符串转换为yyyy-MM-dd HH:mm:ss字符串，JDK1.7以上版本支持该方法 
     * @param s 
     * @return 
     */  
    public static String DateString2formatString(String s)  
    {  
        String str="";  
        try  
        {  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");  
            Date date=sd.parse(s);  
            str=sdf.format(date);  
        }  
        catch(Exception e)  
        {  
           
            System.out.println(e.getMessage());  
            return str;  
        }  
        return str;  
    }  
}
